﻿using RAIN.Core;
using RAIN.Serialization;
using UnityEngine;
namespace RAIN.Motion
{
	[RAINSerializableClass]
	public class NavMeshMotor : BasicMotor
	{
		NavMeshAgent _agent;
		Vector3 _currentTarget;
		public override void AIInit()
		{
			base.AIInit();
			_agent = _ai.Body.GetComponent<NavMeshAgent>();
			CloseEnoughDistance = DefaultCloseEnoughDistance;
		}
		/*public override void ReInitialize()
		{
		}*/
		public override void UpdateMotionTransforms()
		{
			_ai.Kinematic.Position = this._ai.Body.transform.position;
		}
		/*public override void ApplyMotionTransforms()
		{
		}
		public override bool MoveTo(Vector3 position)
		{
			moveTarget.VectorTarget = position;
			//Target = position;
			return this.Move();
		}*/
		public override bool Move()
		{
			Debug.Log ("MOVING " + moveTarget.VectorTarget);
			if (_agent == null || moveTarget.VectorTarget == Vector3.zero)
			{
				return false;
			}
			if (_currentTarget != moveTarget.VectorTarget)
			{
				//Debug.Log(”Set destination”);
				_currentTarget = moveTarget.VectorTarget;
				NavMeshPath path = new NavMeshPath();
				_agent.CalculatePath(_currentTarget, path);
				if (path.status != NavMeshPathStatus.PathPartial && path.status != NavMeshPathStatus.PathInvalid) {
					_agent.SetDestination(moveTarget.VectorTarget);
					//_agent.SetPath(path);
				}else{
					Debug.Log("ERRORINPATH");
				}
			}
			if (!_agent.pathPending)
			{
				//Debug.Log(_agent.remainingDistance);
				if (_agent.remainingDistance <= CloseEnoughDistance)
				{
					//Debug.Log("sucess");
					return true;
				}
			}
			return false;
		}

		public override void Stop()
		{
			_agent.Stop();
		}

		/*public override bool IsAtMoveTarget {
			get {
				if (!_agent.pathPending)
				{
					Debug.Log(_agent.remainingDistance);
					if (_agent.remainingDistance <= CloseEnoughDistance)
					{
						Debug.Log("sucess");
						return true;
					}
				}
				return false;
			}
		}*/
	}
}